import { useEffect, useState, useRef } from 'react';
import { useColorScheme } from 'react-native';
import usePlanStore from '../store/planStore';
import { getTheme } from '../styles/themes';
import { getActualTheme, getCurrentSeason, subscribeToSystemTheme } from '../utils/themeUtils';
import { THEME_MODE } from '../utils/constants';

/**
 * 主题 Hook
 * 返回当前主题对象和主题信息
 */
export const useTheme = () => {
  const { settings, updateSettings } = usePlanStore();
  const systemColorScheme = useColorScheme();
  const [systemTheme, setSystemTheme] = useState(systemColorScheme || 'light');
  const hasMigratedRef = useRef(false);

  // 监听系统主题变化
  useEffect(() => {
    const unsubscribe = subscribeToSystemTheme((theme) => {
      setSystemTheme(theme);
    });
    return unsubscribe;
  }, []);

  // 如果之前选择了 TIME 模式，自动迁移到 AUTO（向后兼容，只执行一次）
  useEffect(() => {
    if (!hasMigratedRef.current && settings.theme === THEME_MODE.TIME) {
      hasMigratedRef.current = true;
      updateSettings({ theme: THEME_MODE.AUTO });
    }
  }, [settings.theme, updateSettings]);

  // 获取实际主题模式（TIME 模式已迁移到 AUTO，这里保持向后兼容）
  const actualThemeMode = getActualTheme(settings.theme);
  
  // 获取当前季节（仅在浅色模式下应用季节主题）
  const season = actualThemeMode === 'light' ? getCurrentSeason() : null;

  // 获取主题对象
  const theme = getTheme(actualThemeMode, season);

  return {
    theme,
    themeMode: actualThemeMode,
    season,
    themeSetting: settings.theme,
  };
};

